import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_terminal_list_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

///楼层指示牌选择播放终端页面
class SmartHomeSelectTerminalPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "SmartHomeSelectTerminalPage";
  final String shid;
  final int totalPicCnt;

  const SmartHomeSelectTerminalPage({Key key, this.shid, this.totalPicCnt}):super(key: key);

  @override
  _SmartHomeSelectTerminalPageState createState() => _SmartHomeSelectTerminalPageState();

  ///跳转方法
  static Future<String> navigatorPush(
      BuildContext context, String shid, int totalPicCnt) {
    return RouterUtils.routeForFutureResult(
      context, SmartHomeSelectTerminalPage(
      shid: shid,
      totalPicCnt: totalPicCnt,
    ),
      routeName: SmartHomeSelectTerminalPage.ROUTER,
    );
  }
}

class _SmartHomeSelectTerminalPageState extends BaseState<SmartHomeSelectTerminalPage>{
  bool _selectAll = false;
  String _originHsns;
  //新增的hsn
  String _hsns;
  //移除的hsn
  String _removeHsns;
  SmartHomeStoreDetailViewModel _viewModel;
  String _searchStr;
  List<TerInfoBean> data;
  bool _firstFlag = true;
  @override
  void initState() {
    super.initState();
    _viewModel = SmartHomeStoreDetailViewModel(this);
    _viewModel.getTerminalList(widget?.shid, _searchStr);
    data = new List();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomPadding: false,
          resizeToAvoidBottomInset: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: CommonPackUpKeyboardWidget(
            child: Column(
              children: <Widget>[
                _toTopBarWidget(),
                _toSearchWidget(),
                Expanded(
                  child: _toPlaceHolderWidget(),
                ),
                _toConfirmWidget(),
              ],
            ),
          ),
        )
    );
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "请选择",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      backgroundColor: Colors.white,
    );
  }

  ///搜索
  Widget _toSearchWidget(){
    return Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[
          SizedBox(height: 10),
          CommonSearchBarWidget(
            hintText: "搜索",
            onSubmitted: (String searchStr) {
              _searchStr = searchStr;
              _viewModel.getTerminalList(widget?.shid, _searchStr);
            },
            bgColor: Color(0xFFF1F4F8),
            textColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
          ),
          SizedBox(height: 10),
        ],
      ),
    );
  }

  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            emptyStatus: value == PlaceHolderStatusType.empty,
            emptyCustomWidget: _defaultEmptyCustomWidget("暂无内容"),
            errorCustomWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
            errorOnClick: () => _viewModel.getTerminalList(widget?.shid, _searchStr),
            loadingOnClick: () => _viewModel.getTerminalList(widget?.shid, _searchStr),
            child: child,
          );
        },
        child: _toBodyWidget());
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }

  Widget _toBodyWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.terminalListValueNotifier,
        builder: (BuildContext context, TerminalListDataBean detailBean, Widget child){
          if(detailBean != null && detailBean.terInfo != null){
            if(_firstFlag){
              data.clear();
              detailBean.terInfo.forEach((element) {
                if("01" == element?.terflg){
                  data.insert(0, element);
                }else{
                  data.add(element);
                }
              });
            }

            if(_originHsns == null){
              _originHsns = _getHsns();
            }
            _hsns = _getHsns();
            if(StringUtils.isNotEmpty(_hsns) && ((_hsns?.split(",")?.length??0) == (data?.length??0))){
              _selectAll = true;
            }
            _firstFlag = false;
          }
          return _toListWidget();
        }
    );
  }

  ///图片展示栏
  Widget _toListWidget(){
    return ListView.separated(
      padding: EdgeInsets.only(top: 0, bottom: 50),
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return _toListItemWidget(context, index,);
      },
      separatorBuilder: (BuildContext context, int index){
        return SizedBox();
      },
      itemCount: data?.length??0,
    );
  }

  ///item
  Widget _toListItemWidget(BuildContext context, int index, ){
    TerInfoBean itemBean = data?.elementAt(index);
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()  {
        setState(() {
          if("01" == itemBean?.terflg){
            itemBean?.terflg = "00";
          }else{
            itemBean?.terflg = "01";
          }
          _selectAll = _getSelectedCount() == data.length;
          _hsns = _getHsns();
        });
      },
      child: Container(
        height: 87,
        color: Colors.white,
        child: Row(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: Image.asset(
                ("01" == itemBean?.terflg)
                    ? "images/common_selected_ico.png"
                    : "images/common_unselect_ico.png",
                height: 20,
              ),
            ),

            Expanded(child: _toContentWidget(index, itemBean)),
          ],
        ),
      ),
    );
  }

  Widget _toContentWidget(int index, TerInfoBean itemBean) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: [
              Visibility(
                visible: (StringUtils.isEmpty(itemBean?.terminalName) && StringUtils.isEmpty(itemBean?.sideNumber)&& StringUtils.isNotEmpty(itemBean?.hsn)),
                child: Text(
                  // "硬件ID：",
                  "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Expanded(
                child: Text(
                  itemBean?.getTerminalName(index),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Spacer(),
              Visibility(
                child: Container(
                  alignment: Alignment.centerRight,
                  width: 60,
                  child: Text(
                    (itemBean.onOff == null || itemBean.onOff !=1 || itemBean.getTerminalIsOff())?"已关机":"开机状态",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: (itemBean.onOff == null || itemBean.onOff !=1 || itemBean.getTerminalIsOff())
                          ?Color(0xFF8B93A5)
                          :ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 4,
          ),
          Container(
            width: 236,
            child: Text(
              showOriginEmptyStr(itemBean?.position) ?? itemBean?.address ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: Color(0xFF8B93A5),
                fontSize: 12,
              ),
            ),
          ),
          SizedBox(
            height: 4,
          ),
          Text(
            "管理员：${itemBean?.manager ?? "-"}${_getLoginStr(itemBean?.loginName) ?? ""}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Color(0xFF8B93A5),
              fontSize: 12,
            ),
          )
        ],
      ),
    );
  }

  String _getLoginStr(String loginName) {
    if (loginName == null || loginName == "") {
      return null;
    }
    return "（$loginName账号登录）";
  }

  int _getSelectedCount(){
    int count = 0;
    if(data != null){
      data.forEach((element) {
        if("01" == element.terflg){
          count++;
        }
      });
    }
    return count;
  }

  ///确定
  Widget _toConfirmWidget(){
    double bottomH = ScreenUtils.getBottomBarH(context);
    return Container(
      height: 56 + bottomH,
      padding: EdgeInsets.only(bottom: bottomH),
      color: Colors.white,
      child: Row(
        children: <Widget>[
          GestureDetector(
            onTap: (){
              setState(() {
                data.forEach((element) {
                  if(_selectAll){
                    element.terflg = "00";
                  }else{
                    element.terflg = "01";
                  }
                });
                _selectAll = !_selectAll;
                _hsns = _getHsns();
              });
            },
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: Text(
                _selectAll?"全不选":"全选",
                style: TextStyle(
                  fontSize: 15,
                  color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                ),
              ),
            ),
          ),
          Visibility(
            visible: _getSelectedCount() > 0,
            child: Text(
              "已选${_getSelectedCount()}终端",
              style: TextStyle(
                fontSize: 12,
                color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              ),
            ),
          ),
          Spacer(),
          CommonFixedHeightConfirmButtonWidget(
            isAlive: _originHsns != _hsns,
            height: 36,
            width: 90,
            margin: const EdgeInsets.symmetric(horizontal: 15),
            unSelectBgColor: Color(0xFFCFD4DB),
            selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            unSelectTextStyle: TextStyle(
              color: Colors.white,
              fontSize: 15,
            ),
            selectedTextStyle: TextStyle(
              color: Colors.white,
              fontSize: 15,
              // fontWeight: FontWeight.w600
            ),
            text: "确定",
            onTap: ()async{
              if(_originHsns == _hsns){
                return;
              }
              // if((widget?.totalPicCnt??0) < 1){
              //   CommonISeeDialog.navigatorPushDialog(context,
              //     content: "您还没有创建任何内容，暂不支持投屏至播放设备",
              //     confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              //     titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              //     contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              //     widgetBgColor: Colors.white,
              //   );
              //   return;
              // }
              // _viewModel.pushSmartHome(context, widget?.shid, _getAddHsns(), _getRemoveHsns(), (){
              //   RouterUtils.pop(context);
              // });
              // RouterUtils.pop(context, result: _getHsns());

              _viewModel.setSmartHomeToTerminal(context, "00", widget?.shid, _getAddHsns(), _getRemoveHsns(), () {
                RouterUtils.pop(context);
              });
            },
          ),
        ],
      ),
    );
  }

  String _getHsns(){
    String hsns = "";
    data.forEach((element) {
      if("01" == element.terflg){
        hsns += element.hsn;
        hsns += ",";
      }
    });
    if(StringUtils.isNotEmpty(hsns)){
      hsns = hsns.substring(0, hsns.length-1);
    }
    return hsns;
  }

  String _getAddHsns(){
    List<String> originList = _originHsns?.split(",");
    if(originList == null || originList.isEmpty){
      return _hsns;
    }
    String hsns = "";
    data.forEach((element) {
      if("01" == element.terflg && !originList.contains(element.hsn)){
        hsns += element.hsn;
        hsns += ",";
      }
    });
    if(StringUtils.isNotEmpty(hsns)){
      hsns = hsns.substring(0, hsns.length-1);
    }
    return hsns;
  }

  String _getRemoveHsns(){
    List<String> originList = _originHsns?.split(",");
    if(originList == null || originList.isEmpty){
      //如果原始的数据为空，那么此次没有要移除的
      return "";
    }

    List<String> hsnList = _hsns?.split(",");
    if(hsnList == null || hsnList.isEmpty){
      //如果选中的没有数据，那么移除的就是原始选中的
      return _originHsns??"";
    }

    String hsns = "";
    data.forEach((element) {
      if(originList.contains(element.hsn) && !hsnList.contains(element.hsn)){
        //原始数据有，选中的没有，代表要移除
        hsns += element.hsn;
        hsns += ",";
      }
    });
    if(StringUtils.isNotEmpty(hsns)){
      hsns = hsns.substring(0, hsns.length-1);
    }
    return hsns;
  }


}